
#include "opticalflow.hpp"

#include <opencv2/imgproc/imgproc.hpp>
#include "opencv2/legacy/legacy.hpp"
#include "opencv2/highgui/highgui.hpp"
using namespace cv;

OpticalFlow::OpticalFlow(Process *pro):Observer(pro)
{
}

OpticalFlow::~OpticalFlow()
{
	Log("Release Optical Flow");
	_pro->Detach(this);
}

void OpticalFlow::Update(Image &image)
{
	Image pre= _pro->prv_image;
	if(out_image.data == 0)
		out_image = Image(image.width, image.height, (int)image.channel+1);
	if(pre.data != 0)
	{
		//for(int i=0;i<image.height*image.width*(image.channel+1);i++)
		//	out_image.data[i] =3* abs(_pro->prv_image.data[i] - image.data[i]);
		Mat prv(image.height, image.width, CV_8UC3, pre.data);
		cvtColor(prv, prv, CV_BGR2GRAY);
		Mat img(image.height, image.width, CV_8UC3, image.data);
		cvtColor(img, img, CV_BGR2GRAY);
		
		IplImage *grey = new IplImage(img), *prev_grey = new IplImage(prv); 
		IplImage *eig = 0, *temp = 0 ,*Mag , *Angle;

		eig = cvCreateImage( cvGetSize(grey), 32, 1 );
 		temp = cvCreateImage( cvGetSize(grey), 32, 1 );
		Mag  = cvCreateImage( cvGetSize(grey), 32, 1 );
		Angle = cvCreateImage( cvGetSize(grey), 32, 1 );

		cvCalcOpticalFlowLK(prev_grey,grey,cvSize(5,5),eig,temp);
		cvCartToPolar( eig, temp, Mag, Angle, false );
		Mat out = Mat(Mag);
		out.convertTo(out, CV_8UC1, 255);

		Image(image.width, image.height, 1, (unsigned char*)out.data).Convert(out_image);
		
		cvReleaseImage( &eig ); 
		cvReleaseImage( &temp ); 
		cvReleaseImage( &Mag ); 
		cvReleaseImage( &Angle ); 		
		
		//for(int i=0;i<image.height*image.width;i++)
		//	out_image.data[3*i] = out_image.data[3*i+1] = out_image.data[3*i+2] = 
	}
}
